import axios from "axios";
import qs from 'qs';
import { MessagePlugin } from 'tdesign-vue-next';

const service = axios.create({
    baseURL:'//127.0.0.1:8080',
    timeout:5000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
      }
});

service.interceptors.request.use(config=>{
    const token = localStorage.getItem("token")
    if(token) {
        config.headers.Authorization = `Bearer ${token}`;
    }

    if(config.method==='get' || config.method==='delete'){
        config.paramsSerializer = params => {
            return qs.stringify(params,{arrayFormat:'repeat'});
        }
    }
    return config
},error=>{
    return  Promise.reject(error);
})


service.interceptors.response.use(response=>{

    const res = response.data;
    
    // 根据自定义状态码处理（这里假设状态码200表示成功）
    if (response.status === 200) {
      return res;
    } else {
      // 处理其他状态码
      MessagePlugin.error(res.message || 'Error');
      return Promise.reject(new Error(res.message || 'Error'));
    }
    
},error=>{
    let errorMessage = '请求失败';
    if(error.response){
        switch(error.response.status){
            case 401:
                errorMessage = '身份验证失败，请重新登录';
                // 清除token并跳转登录
                localStorage.removeItem('token');
                router.push('/login');
                break;
            case 403:
                errorMessage = '拒绝访问';
                break;
            case 404:
                errorMessage = '资源不存在';
                break;
            case 500:
                errorMessage = '服务器错误';
                break;
        }
    }else if (error.request) {
        errorMessage = '请求未响应';
      } else {
        errorMessage = error.message;
      }
      
    MessagePlugin.error(errorMessage);
    return Promise.reject(error);
})


const request = {
    get(url,params,config={}){
        return service({method:'get',url,params,...config})
    },
    post(url,data,config={}){
        return service({method:'post',url,data,...config})
    },
    put(url,data,config={}){
        return service({method:'put',url,data,...config})
    },
    delete(url,params,config={}){
        return service({method:'delete',url,params,...config})
    }
}

export default request;